package com.leoman.plz_p.views.homepage;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.leoman.plz_p.R;
import com.leoman.plz_p.adapter.CourseCommentAdapter;
import com.leoman.plz_p.adapter.CourseTestAdapter;
import com.leoman.plz_p.adapter.SectionAdapter;
import com.leoman.plz_p.constants.Constants;
import com.leoman.plz_p.interfaces.CourseDetailView;
import com.leoman.plz_p.module.bean.BookListBean;
import com.leoman.plz_p.module.bean.CourseBean;
import com.leoman.plz_p.module.bean.CourseCommentBean;
import com.leoman.plz_p.module.bean.ExamInfoBean;
import com.leoman.plz_p.module.bean.MapData;
import com.leoman.plz_p.module.bean.TestBean;
import com.leoman.plz_p.presenter.CourseDetailPresenter;
import com.leoman.plz_p.utils.authority.AuthorityContext;
import com.leoman.plz_p.views.WebActivity;
import com.leoman.plz_p.views.study.AnswerActivity;
import com.leoman.plz_p.weidget.CircleProgressBar;
import com.leoman.plz_p.weidget.NavBar;
import com.leoman.plz_p.weidget.NoScrollWebView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.xiao.nicevideoplayer.NiceVideoPlayer;
import com.xiao.nicevideoplayer.NiceVideoPlayerManager;
import com.xiao.nicevideoplayer.TxVideoPlayerController;

import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import cn.com.corelib.base.BaseActivity;
import cn.com.corelib.utils.ToastMgr;
import cn.com.corelib.views.NoScrollingListView;

/**
 * 课程详情
 */
public class CourseDetailActivity extends BaseActivity<CourseDetailView, CourseDetailPresenter> implements CourseDetailView, SectionAdapter.onItemClick {


    @Bind(R.id.nav)
    NavBar nav;
    @Bind(R.id.tv_study_point)
    TextView tvStudyPoint;
    @Bind(R.id.tv_book)
    TextView tvBook;
    @Bind(R.id.web_point_content)
    NoScrollWebView wbPointContent;
    @Bind(R.id.ll_pint)
    LinearLayout llPint;
    @Bind(R.id.ls_book)
    ListView lsBook;
    @Bind(R.id.custom_progress)
    CircleProgressBar customProgress;
    @Bind(R.id.ll_book)
    LinearLayout llBook;
    @Bind(R.id.rl_study_point)
    RelativeLayout rlStudyPoint;
    @Bind(R.id.rl_book)
    RelativeLayout rlBook;
    @Bind(R.id.tv_recent_study)
    TextView tvRecentStudy;
    @Bind(R.id.ls_commit)
    NoScrollingListView lsCommit;
    @Bind(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @Bind(R.id.et_comment)
    EditText etComment;
    @Bind(R.id.tv_comment_now)
    TextView tvCommentNow;
    @Bind(R.id.tv_introduce)
    TextView tvIntroduce;
    @Bind(R.id.rl_introduce)
    RelativeLayout rlIntroduce;
    @Bind(R.id.ll_introduce)
    LinearLayout llIntroduce;

    @Bind(R.id.ls_test)
    ListView lsTest;
    @Bind(R.id.tv_course_name)
    TextView tvCourseName;
    @Bind(R.id.tv_view_count)
    TextView tvViewCount;

    private CourseTestAdapter testAdapter;

    private int pageIndex = 1;

    private SectionAdapter adapter;

    private CourseCommentAdapter commentAdapter;

    private CourseBean course;


    public static Intent getLaunchIntent(Context context, CourseBean bean) {
        Intent intent = new Intent(context, CourseDetailActivity.class);
        intent.putExtra(Constants.KEY_COURSE, bean);
        return intent;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.ac_course_detail;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        course = (CourseBean) getIntent().getSerializableExtra(Constants.KEY_COURSE);
        initMedia(course.getUrl(),course.getImage());
        addListeners();
        initRefresh();
        commentAdapter = new CourseCommentAdapter(getViewContext());
        testAdapter = new CourseTestAdapter(getViewContext());
        lsCommit.setAdapter(commentAdapter);
        lsTest.setAdapter(testAdapter);
        nav.setTitle(course.getName());
        if (!TextUtils.isEmpty(course.getPoint())) {
            course.setPoint(course.getPoint().replace("<img", "<img style='max-width:100%;height:auto;'"));
            wbPointContent.loadDataWithBaseURL("", course.getPoint(), "text/html", "utf-8", "");
        }
        tvCourseName.setText(course.getName());
        tvViewCount.setText(course.getPlaynum() + "");
        getPresenter().getBookList(String.valueOf(course.getId()));
        getPresenter().getComment(course.getId() + "", pageIndex, 12);
        getPresenter().getTestList(String.valueOf(course.getId()));
        if (AuthorityContext.getContext().isLoggedIn()) {
            getPresenter().getRecentStudy(String.valueOf(course.getId()));
        }

    }

    private void initMedia(String url,String cover){
        NiceVideoPlayer mNiceVideoPlayer = (NiceVideoPlayer) findViewById(R.id.nice_video_player);
        mNiceVideoPlayer.setPlayerType(NiceVideoPlayer.TYPE_IJK); // or NiceVideoPlayer.TYPE_NATIVE
        mNiceVideoPlayer.setUp(TextUtils.isEmpty(url)?"https://123.mp4":url, null);
        TxVideoPlayerController controller = new TxVideoPlayerController(this);
        controller.setTitle("");
        Glide.with(this)
                .load(cover)
                .placeholder(R.mipmap.place_icon)
                .centerCrop()
                .into(controller.imageView());
        mNiceVideoPlayer.setController(controller);
    }

    @Override
    protected CourseDetailPresenter createPresenter() {
        return new CourseDetailPresenter();
    }

    private void initRefresh() {
        refreshLayout.setEnableRefresh(false);
        refreshLayout.setEnableLoadmore(true);
        refreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                pageIndex += 1;
                getPresenter().getComment(course.getId() + "", pageIndex, 12);
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {

            }
        });
    }

    private void addListeners() {
        rlStudyPoint.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setTextSelectOff(tvBook);
                setTextSelectOff(tvIntroduce);
                setTextSelectOn(tvStudyPoint);
                llPint.setVisibility(View.VISIBLE);
                llBook.setVisibility(View.GONE);
                llIntroduce.setVisibility(View.GONE);

            }
        });
        rlBook.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setTextSelectOff(tvStudyPoint);
                setTextSelectOff(tvIntroduce);
                setTextSelectOn(tvBook);
                llPint.setVisibility(View.GONE);
                llBook.setVisibility(View.VISIBLE);
                llIntroduce.setVisibility(View.GONE);
                customProgress.setProgress(2);

            }
        });
        rlIntroduce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setTextSelectOff(tvStudyPoint);
                setTextSelectOff(tvBook);
                setTextSelectOn(tvIntroduce);
                llPint.setVisibility(View.GONE);
                llBook.setVisibility(View.GONE);
                llIntroduce.setVisibility(View.VISIBLE);
            }
        });
        adapter = new SectionAdapter(getViewContext());
        lsBook.setAdapter(adapter);
        adapter.setOnItemClick(CourseDetailActivity.this);
    }

    @OnClick({R.id.tv_comment_now})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_comment_now:
                if (AuthorityContext.getContext().checkAuthority(getViewContext())) {
                    if (isEmpty(etComment)) {
                        ToastMgr.show("请输入评论");
                        return;
                    }
                    getPresenter().sendComment(course.getId() + "", getText(etComment));
                }
                break;
        }
    }

    private void setTextSelectOn(TextView textView) {
        textView.setTextColor(getResources().getColor(R.color.colorPrimary));
    }

    private void setTextSelectOff(TextView textView) {
        textView.setTextColor(getResources().getColor(R.color.black));
    }

    @Override
    public void obtainRecentStudy(MapData data) {
        tvRecentStudy.setText("最近在学：" + data.name);
    }

    @Override
    public void obtainBookList(List<BookListBean> data) {
        adapter.replaceAll(data);
    }

    @Override
    public void obtainStudyNumber(String number) {
//        nav.setRightText("学习人数:" + number);
    }

    @Override
    public void obtainExamIds(List<String> ids, ExamInfoBean bean) {
        startActivity(AnswerActivity.getLaunchIntent(getViewContext(), bean.getTitle(), ids.toString().replace("[", "").replace("]", ""), bean.getId() + "", bean.getExaminTime(), false, false, false, false));
    }

    @Override
    public void obtainCommentList(List<CourseCommentBean> rows) {
        if (rows != null && rows.size() > 0) {
            if (pageIndex == 1) {
                commentAdapter.clear();
            }
            commentAdapter.addAll(rows);
            refreshLayout.finishLoadmore(true);
        } else {
            refreshLayout.finishLoadmoreWithNoMoreData();
        }
    }

    @Override
    public void obtainCommentSuccess() {
        ToastMgr.show("评论成功");
        pageIndex = 1;
        getPresenter().getComment(course.getId() + "", pageIndex, 12);
    }

    @Override
    public void obtainTestList(List<TestBean.ListBeanX> list) {
        testAdapter.replaceAll(list);
    }


    @Override
    public void onSafeClick(int parent, int position) {
        if (AuthorityContext.getContext().checkAuthority(getViewContext()))
            startActivity(PointIntroduceActivity.getLaunchIntent(getViewContext(), adapter.getItem(parent).getList().get(position).getCourseChapterId() + "", course.getId() + "", "1"));
    }

    @Override
    public void onRequestClick(int parent, int position) {
        if (AuthorityContext.getContext().checkAuthority(getViewContext()))
            startActivity(PointIntroduceActivity.getLaunchIntent(getViewContext(), adapter.getItem(parent).getList().get(position).getCourseChapterId() + "", course.getId() + "", "2"));
    }

    @Override
    public void onVideoClick(int parent1, int parent2, int child) {
        startActivity(PointDetailActivity.getLaunchIntent(getViewContext(), course.getId() + "", adapter.getItem(parent1).getList().get(parent2).getList().get(child).getCourseChapterId() + ""));
    }

    @Override
    public void onExamClick(int parent1, int parent2, int child) {
        startActivity(WebActivity.getLaunchIntent(getViewContext(), "", "http://47.99.127.57:8080/3d_test/index.html", "", true, true));
    }

    @Override
    public void onTestClick(int parent1, int parent2, int child) {
        if (AuthorityContext.getContext().checkAuthority(getViewContext()))
            getPresenter().getCourseExamIds(course.getId() + "", adapter.getItem(parent1).getList().get(parent2).getList().get(child).getCourseChapterId() + "");
    }


    @Override
    protected void onStop() {
        super.onStop();
        // 在onStop时释放掉播放器
        NiceVideoPlayerManager.instance().releaseNiceVideoPlayer();
    }
    @Override
    public void onBackPressed() {
        // 在全屏或者小窗口时按返回键要先退出全屏或小窗口，
        // 所以在Activity中onBackPress要交给NiceVideoPlayer先处理。
        if (NiceVideoPlayerManager.instance().onBackPressd()) return;
        super.onBackPressed();
    }

}